package com.example.uploadhealth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.uploadhealth.domain.ResponseResult;
import com.example.uploadhealth.domain.eneity.User;
import com.example.uploadhealth.enums.AppHttpCodeEnum;
import com.example.uploadhealth.exception.SystemException;
import com.example.uploadhealth.mapper.UserMapper;
import com.example.uploadhealth.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public ResponseResult getAllUser() {
        List<User> list = list();
        return ResponseResult.okResult(list);
    }

    @Override
    public ResponseResult register(User user) {
        if(!StringUtils.hasText(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_IS_NULL);
        }
        if(!StringUtils.hasText(user.getPassword())){
            throw new SystemException(AppHttpCodeEnum.PASSWORD_IS_NULL);
        }
        if(!StringUtils.hasText(user.getClassName())){
            throw new SystemException(AppHttpCodeEnum.CLASS_IS_NULL);
        }
        if(!StringUtils.hasText(user.getNickName())){
            throw new SystemException(AppHttpCodeEnum.NICKNAME_IS_NULL);
        }
        if(userNameIsExit(user)>0){
            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
        }
        String encode = passwordEncoder.encode(user.getPassword());
        user.setPassword(encode);
        save(user);
        return ResponseResult.okResult();
    }

    private int userNameIsExit(User user) {
        LambdaQueryWrapper<User> queryWrappe=new LambdaQueryWrapper<>();
        queryWrappe.eq(User::getUserName,user.getUserName());
        int count = count(queryWrappe);
        return count;
    }
}
